package com.etc.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import com.etc.common.VerifyCode;
import com.etc.pojo.UserInfo;
import com.etc.service.IUserService;

// 不可用 RestController
@Controller
public class UserController {

    @Autowired
    IUserService service;
    
    @PostMapping("regist.action")
    public String regist(UserInfo ui) { // String uname, String password
        
        service.addUser(ui);
        
        // 相当于forward功能
        return "login"; // 视图解析器  前缀/   后缀.jsp == /login.jsp 
    }
    
    @GetMapping("user/random.action")
    public void randimg(HttpServletRequest request, HttpServletResponse rep, HttpSession session) throws IOException {
        OutputStream os = rep.getOutputStream();
        String tmp = VerifyCode.drawRamdomText(os);
        System.out.println(tmp);
        session.setAttribute("random", tmp);
    }
    
    @PostMapping("login.action")
    public String login(@Valid UserInfo vo, BindingResult result, HttpSession session, Model model) {
        
        if (result.hasErrors()) {   
            List<ObjectError> errors = result.getAllErrors();   
            for (ObjectError e : errors) {
                // model 相当于 request.setAttri...中的数据
                System.out.println(e.getCode());
                System.out.println(e.getObjectName());
                model.addAttribute("msg", e.getDefaultMessage());
                return "login";
            }
        }
        // check 验证码
        if (!vo.getRandom().equalsIgnoreCase(String.valueOf(session.getAttribute("random")))) {
            // model 相当于 request.setAttri...中的数据
            model.addAttribute("msg", "验证码错误");
            return "login";
        }
        
        Map ui = service.findByUname(vo.getUname());
        
        if (ui == null) {
            // model 相当于 request.setAttri...中的数据
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } else if (!ui.get("psd").equals(vo.getPassword())) {
            model.addAttribute("msg", "用户名存在，密码错误");
            return "login";
        }
        session.setAttribute("ui", ui);
        // 重定向？？？
        return "redirect:welcome.jsp";
    }
}
